﻿using mscook.core;
using mscook.core.domain;
using mscook.core.services;
using mscook.mvc.core;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text.RegularExpressions;
using mscook.mvc.Areas.weblogin.Models;
using System.Linq.Expressions;
using mscook.core.repositories;
namespace mscook.mvc.Areas.weblogin.Controllers
{
    public class magazineController : BaseController
    {
        protected IMagazineService iMagazineService;
        private IArticleTemplateFactory articleTemplateFactory;
        private IImageSettingFactory iImageSettingFactory;
        private IResourceBonusSettingService iResourceBonusSettingService;
        private ILoginUserService iLoginUserService;
        private IRelativeLinkRepository iRelativeLinkRepository;
        private readonly string SectionName = "Magazine";
        //
        // GET: /weblogin/magazine/
        public magazineController(IRelativeLinkRepository iRelativeLinkRepository, IMagazineService iMagazineService, IArticleTemplateFactory articleTemplateFactory, IImageSettingFactory iImageSettingFactory, ILoginUserService iLoginUserService, IResourceBonusSettingService iResourceBonusSettingService)
            : base(iLoginUserService)
        {
            this.iLoginUserService = iLoginUserService;
            this.iMagazineService = iMagazineService;
            this.articleTemplateFactory = articleTemplateFactory;
            this.iImageSettingFactory = iImageSettingFactory;
            this.iResourceBonusSettingService = iResourceBonusSettingService;
            this.iRelativeLinkRepository = iRelativeLinkRepository;

        }

        public ActionResult Index(string nowPageNum, string per = "", string year = "", string month = "")
        {
            Expression<Func<Magazine, bool>> select_expression = o => (string.IsNullOrEmpty(year) || o.Year.Equals(year))
            && (string.IsNullOrEmpty(month) || o.Volume.Equals(month));

            PageBreakHelper pageHelper = new PageBreakHelper();
            pageHelper.Init(nowPageNum, per);
            long total = 0;
            IList<Magazine> magazineList = iMagazineService.SelectPageListByExpressions(pageHelper.Start, pageHelper.PerValue, out total, select_expression);
            pageHelper.SetViewDataKeys(ViewData, ViewBag, total);
            InitNavBar();


            ViewData["year"] = year;
            ViewData["month"] = month;
            ViewData["nowPageNum"] = nowPageNum;
            ViewData["per"] = per;

            return View(magazineList);
        }
        public ActionResult ArticleIndex(string id, int year, int month)
        {
            ArticleIndexModel articleIndexModel = new ArticleIndexModel();
            articleIndexModel.ArticlePublishDetails = articleTemplateFactory.SelectArticlePublishDetails(year, month);
            articleIndexModel.ResourceBonusSettings = iResourceBonusSettingService.SelectByAriticKeyAndType(year.ToString(), month.ToString(), PurchasedCategory.Article);

            ViewData["Year"] = year;
            ViewData["Month"] = month;

            InitNavBar();
            return View(articleIndexModel);
        }
        //2013-11-05 basilwang TODO can't bind articleKey


        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Add()
        {
            InitNavBar();
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult Add(Magazine Magazine, string MagazineTypeId)
        {
            if (ModelState.IsValid)
            {
                if (SaveUploadImage(Magazine))
                {
                    SaveResourceType(Magazine, MagazineTypeId);
                    Magazine.ResourceBonusSetting.Bonus = -Math.Abs(Magazine.ResourceBonusSetting.Bonus);
                    Magazine.EntityIndex = int.Parse(Magazine.Year + Magazine.Volume);
                    iMagazineService.SaveOrUpdate(Magazine);

                    return RedirectToIndex();
                }
            }
            return View();
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Edit(string id)
        {
            Magazine Magazine = iMagazineService.Get(id);
            if (Magazine != null)
            {
                MagazineModel magazineModel = new MagazineModel() { Magazine = Magazine };
                magazineModel.ResourceTypes = GetResourceType(Magazine.Id);

                InitNavBar();
                return View(magazineModel);
            }
            //If result is null, redirect to index
            return RedirectToIndex();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult Edit(string id, string MagazineTypeId)
        {

            MagazineModel magazineModel = new MagazineModel();
            magazineModel.Magazine = iMagazineService.Get(id);

            if (ModelState.IsValid)
            {
                SaveResourceType(magazineModel.Magazine, MagazineTypeId);
                UpdateModel(magazineModel);
                magazineModel.Magazine.EntityIndex = int.Parse(magazineModel.Magazine.Year + magazineModel.Magazine.Volume);
                SaveUploadImage(magazineModel.Magazine);
                iMagazineService.SaveOrUpdate(magazineModel.Magazine);
                return RedirectToIndex();
            }
            return View();
        }

        public ActionResult Delete(string id)
        {
            iMagazineService.Delete(id);
            return RedirectToIndex();
        }

        public ActionResult MagazineModal(string nameInput, string idInput, string title, string linkBtn = "", string num = "")
        {
            PageBreakHelper pageHelper = new PageBreakHelper();
            pageHelper.Init(num, "10");
            long total = 0;
            IList<Magazine> magazinelList = iMagazineService.SelectPageList(pageHelper.Start, pageHelper.PerValue, out total, title);
            pageHelper.SetViewDataKeys(ViewData, ViewBag, total);
            ViewData["nameInput"] = nameInput;
            ViewData["idInput"] = idInput;
            ViewData["linkBtn"] = linkBtn;

            return View(magazinelList);
        }

        public ActionResult ArticleDelete(int year, int month, int index, string alias)
        {
            articleTemplateFactory.DeleteArticle(year, month, index, alias);
            return RedirectToIndex();
        }


        private bool SaveUploadImage(Magazine Magazine)
        {
            if (Request.Files.Count > 0)
            {
                HttpPostedFileBase file = Request.Files.Get(0);
                if (file.ContentLength != 0)
                    Magazine.ImageName = iImageSettingFactory.CreateBatchSizedImage(SectionName, file.FileName, file.InputStream);
                return true;
            }
            return false;
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult GenTemplate(ArticleKey articleKey)
        {

            GenTemplateModel genTemplateModel = new GenTemplateModel() { ArticleKey = articleKey };

            RelativeLink relativeLink = iRelativeLinkRepository.GetByResourceId(articleKey.Id());

            //ViewData[ViewDataKeys.YEAR] = articleKey.Year;
            //ViewData[ViewDataKeys.MONTH] = articleKey.Month;
            //ViewData[ViewDataKeys.ALIAS] = string.IsNullOrEmpty(articleKey.Alias) ? null : articleKey.Alias;
            ArticlePublishDetail articlepublish = articleTemplateFactory.SelectArticlePublishDetailBy(articleKey.Year, articleKey.Month, articleKey.Alias);

            genTemplateModel.RelativeLink = relativeLink;
            genTemplateModel.Index = articlepublish != null ? articlepublish.ArticleKey.Index.ToString() : null;


            //ViewData[ViewDataKeys.INDEX] = articlepublish != null ? articlepublish.ArticleKey.Index.ToString() : null;
            InitNavBar();
            return View(genTemplateModel);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult GenTemplate(ArticleKey articleKey, FormCollection formValues, bool edit = true)
        {
            string source = string.Empty;

            string[] componentArray = { "titleChoice", "authorChoice", "sourceChoice", "contentChoice", "relatedChoice", "phraseChoice" };
            string value = formValues["title"];

            // bool isEdit=Boolean.Parse(formValues["isEdit"]);
            if (edit)
            {
                source = articleTemplateFactory.SelectHtmlSnippetsOfUnits(articleKey);
            }
            else
            {
                if (articleTemplateFactory.SelectArticlePublishDetailBy(articleKey.Year, articleKey.Month, articleKey.Alias) == null)
                {
                    IList<ArticleComponent> ArticleComponentList = new List<ArticleComponent>();
                    string version = "1";
                    foreach (string component in componentArray)
                    {

                        ArticleComponent ArticleComponent = new ArticleComponent(component, formValues[component], version);
                        ArticleComponentList.Add(ArticleComponent);
                    }
                    source = articleTemplateFactory.SelectHtmlSnippetsOfUnits(ArticleComponentList, articleKey);
                }
                else
                {
                    source = "<div class='control-group'>别名重复，请修改</div>";
                }
            }



            //ArticleKey articleKey = new ArticleKey(2013, 10, "guowenjun",true);

            return Content(source);
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult SaveTemplate(ArticleKey articleKey, DataOfUnit dataOfUnit, FormCollection collections, RelativeLink relativeLink = null)
        {
            HttpPostedFileBase file = Request.Files.Get("content_image");
            if (file != null && file.FileName != string.Empty)
            {
                dataOfUnit.content_image = iImageSettingFactory.CreateBatchSizedImage("Article", file.FileName, file.InputStream);
            }
            else if (collections["existed_content_image"] != null)
            {
                dataOfUnit.content_image = collections["existed_content_image"];
            }
            else
            {
                dataOfUnit.content_image = string.Empty;
            }


            List<RelatedDataOfUnit> itemList = new List<RelatedDataOfUnit>();
            var validRelatedContents = from s in collections.AllKeys
                                       where s.IndexOf("related_content[") != -1 && s != "related_content[0]"
                                       select new string[] { s, string.Format("related_content_image[{0}]", new Regex("\\d").Match(s).Value), string.Format("existed_related_content_image[{0}]", new Regex("\\d").Match(s).Value) };
            foreach (var element in validRelatedContents)
            {
                file = Request.Files.Get(element[1]);
                string related_content_image;
                if (file != null && file.FileName != string.Empty)
                {
                    related_content_image = iImageSettingFactory.CreateBatchSizedImage("Article", file.FileName, file.InputStream);
                }
                else if (collections[element[2]] != null)
                {
                    related_content_image = collections[element[2]];
                }
                else
                {
                    related_content_image = string.Empty;
                }
                string content = collections[element[0]].Replace(" ", "&nbsp;").Replace("\r\n", "<br/>");

                dataOfUnit.related.Add(new RelatedDataOfUnit()
                {
                    related_content = content,
                    related_content_image = related_content_image
                });
            }

            /*
             * 0:Content 内容
             * 1:内容图片
             * 2：已存在图片
             * */

            var validPhraseContents = from s in collections.AllKeys
                                      where s.IndexOf("phrase_content[") != -1 && s != "phrase_content[0]"
                                      select new string[] { s, string.Format("phrase_content_image[{0}]", new Regex("\\d").Match(s).Value), string.Format("existed_phrase_content_image[{0}]", new Regex("\\d").Match(s).Value) };
            foreach (var element in validPhraseContents)
            {
                file = Request.Files.Get(element[1]);
                string phrase_content_image;
                if (file != null && file.FileName != string.Empty)
                {
                    phrase_content_image = iImageSettingFactory.CreateBatchSizedImage("Article", file.FileName, file.InputStream);
                }
                else if (collections[element[2]] != null)
                {
                    phrase_content_image = collections[element[2]];
                }
                else
                {
                    phrase_content_image = string.Empty;
                }

                string content = collections[element[0]].Replace(" ", "&nbsp;").Replace("\r\n", "<br/>");
                dataOfUnit.phrase.Add(new PhraseDataOfUnit()
                {

                    phrase_content = content,
                    phrase_content_image = phrase_content_image
                });
            }
            if (dataOfUnit.content != null)
            {
                dataOfUnit.content = dataOfUnit.content.Replace(" ", "&nbsp;");
                dataOfUnit.content = Regex.Replace(dataOfUnit.content, "\r\n", "<br/>");
            }

            // dataOfUnit.content = dataOfUnit.content.Replace(@"\\r\\n", "1");
            //articleKey = new ArticleKey(2013, 10, "guowenjun", true);
            articleTemplateFactory.PostDataOfUnit(dataOfUnit, articleKey);

            //2013-12-20 Lampard 增加相关链接

            if (relativeLink != null && !string.IsNullOrEmpty(relativeLink.LinkId))
            {
                //relativeLink.ResourceId = articleKey.Id();
                RelativeLink exitLink = iRelativeLinkRepository.GetByResourceId(articleKey.Id());
                if (exitLink == null)
                {
                    exitLink = new RelativeLink();
                }
                exitLink.LinkName = relativeLink.LinkName;
                exitLink.LinkId = relativeLink.LinkId;
                exitLink.LinkType = relativeLink.LinkType;
                exitLink.ResourceId = articleKey.Id();

                iRelativeLinkRepository.SaveOrUpdate(exitLink);

            }

            return Content("文章编辑完成，点击发布按钮后读者可以在网站查看");
        }

        public string Publish(ArticleKey articleKey)//发布方法
        {
            articleTemplateFactory.GenerateHtmlFile(articleKey);
            return true.ToString().ToLower();
        }
    }
}
